<?php
class CEstore{
	public $pathThemeDefault;
	public $estore_id;
	public $listTheme;
	public $themeCurrent;
	public $informationEstore;
	public $estore;

	/**
	 *
	 * @var current instance of estore
	 */
	private static $instance;

	/**
	 * Getn current instance of CEstore
	 *
	 * @return CEstore
	 */
	public static function getInstance() {
		if (null==self::$instance) {
			$estore_id = request('estore_id');
			if (!$estore_id) return null;
			$estore_id = 'estorecache'.$estore_id;
			if (DEBUG || !(self::$instance = CSystem::$cachedata->get($estore_id))){
				self::$instance = new CEstore($estore_id, self::$instance);
				CSystem::$cachedata->set($estore_id, self::$instance);
			}

			// Neu thuoc theme mac dinh cua vimua
			if (self::$instance->estore['themeDefault']){
				CPortal::$current->data['settings']['skin'] = self::$instance->estore['themeCurrent'];
			}
			self::$instance->estore['pathTheme'] = CPortal::$static_url.portal()->skin('estore');
		}
		return self::$instance;
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $options
	 */
	function __construct($options = array()) {
		$this->estore_id = request('estore_id');
		$this->estore = CTable('estore')->select(EAnd(EEqual('code',$this->estore_id), EEqual('status',1)));
		if (empty($this->estore)) throw new Exception('Không tồn tại estore');

		//?????
		$this->pathThemeDefault = CPortal::$root_url.portal()->skin();
		if($this->informationEstore = $this->getInformationEstore() and is_array($this->informationEstore)){
			$this->estore = array_merge($this->estore, $this->informationEstore);
			$this->estore['themeDefault'] = false;
			$this->estore['themeCurrent'] = '';
			if($this->themeCurrent = $this->getThemeCurrent($this->estore['theme'])){
				if(intval($this->estore['theme']) > 1){
					$this->estore['themeCurrent'] = $this->themeCurrent['name'];
					$this->estore['themeDefault'] = true;
				} else {
					$this->estore['themeCurrent'] = unserialize($this->estore['css']);
				}
			} else {
				if(!intval($this->estore['theme'])){
					$this->estore['themeCurrent'] = unserialize($this->estore['css']);
				}
			}
			if($this->estore['css']){
				$this->estore['css'] = unserialize($this->estore['css']);
			}
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $field
	 * @return unknown
	 */
	function getInformationEstore($field = ''){
		if($field){
			return CTable('estore_shop_information')->fields($field)->select(EEqual('shop_id', $this->estore['id']));
		}else{
			return CTable('estore_shop_information')->select(EEqual('shop_id',$this->estore['id']));
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $theme
	 * @return unknown
	 */
	function changeTheme($theme){
		// check quyen change theme
		if($this->checkPermission()){
			if(is_array($theme)){
				$theme = serialize($theme);
				return CTable('estore_shop_information')->update(array('css' => $theme), array('id' => $this->estore['id']));
			}else{
				return CTable('estore_shop_information')->update(array('theme' => $theme, 'css' => ''), array('id' => $this->estore['id']));
			}
		}
	}

	/**
	 * Enter description here...
	 *
	 */
	function getAllTheme(){
		$this->listTheme = CTable('estore_theme')->select_all();
		return $this->listTheme;
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $idTheme
	 * @return unknown
	 */
	function getThemeCurrent($idTheme = 1){
		if($this->themeCurrent = CTable('estore_theme')->fields('name')->select($idTheme)){
			return $this->themeCurrent;
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $blast
	 * @return unknown
	 */
	function updateBlast($blast = ''){
		if (user()->is_login() && user()->id==CEstore()->estore['ceo']){
			if(CTable('estore_shop_information')->update(array('blast'=>$blast),array('id'=>$this->estore['id']))){
				return true;
			} else {
				return false;
			}
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param unknown_type $array
	 * @param unknown_type $obj
	 * @return unknown
	 */
	function array_to_obj($array, &$obj){
		foreach ($array as $key => $value){
			if (is_array($value)){
				$obj->$key = new stdClass();
				$this->array_to_obj($value, $obj->$key);
			}else{
				$obj->$key = $value;
			}
		}
		return $obj;
	}

	/**
	 * Check permission master shop
	 *
	 * @param
	 * @return unknown
	 */
	 function checkPermission(){
	 	if(user()->is_login() and user()->id == $this->estore['ceo']){
			return true;
		}else return false;
	 }
  /**
   * Lấy danh sách sản phẩm mới
   *
   * @param int $store_id shop đang show
   * @return Array list sản phẩm mới
   */
	static function get_new_products($store_id = '')
	{
		$items = array_values(CTable('product')->fields('id,name,category_id,thumbnail,warranty,cache_properties, price')
											   ->select_all(
															EAnd(
																 ELike('category_path', EString('.mobile.')),
																 ELIKE('types',EString('new')),EEqual('reference_id',EString(''))
																,ENE('price',EString(0)),ENE('min_price',EString(0)),
																ENE('market_price',EString(0)),ENE('status',EString(0)),
																ENE('quantity',EString(0)),ENE('thumbnail',EString(''))
															),
															 array('order_by'=>'created_time desc', 'items_per_page'=>2)
		));
		// thêm products nếu chưa đủ 2
		if(count($items) < 2){
			$items = array_merge($items, CTable('product')->fields('id,name,category_id,warranty,thumbnail,cache_properties, price')->select_all(
				EAnd(ELike('category_path', EString('.mobile.')),ENLike('types',EString('new')),EEqual('reference_id',EString(''))
					,ENE('price',EString(0)),ENE('min_price',EString(0)),ENE('market_price',EString(0)),ENE('status',EString(0)),ENE('quantity',EString(0)),ENE('thumbnail',EString(''))),
				array('order_by'=>'created_time desc', 'items_per_page'=>2-count($items))
			));
		}
		// lấy sản phẩm labtop mới nhất
		$laptop_item =  CTable('product')->fields('id,name,category_id,thumbnail,warranty,cache_properties, price')->select(
			EAnd(ELike('category_path', EString('.laptop.')),ELIKE('types',EString('new')),EEqual('reference_id',EString(''))
				,ENE('price',EString(0)),ENE('min_price',EString(0)),ENE('market_price',EString(0)),ENE('status',EString(0)),ENE('quantity',EString(0)),ENE('thumbnail',EString(''))),
			array('order_by'=>'created_time desc', 'items_per_page'=>1)
		);
		if(empty($laptop_item)){
			$laptop_item =  CTable('product')->fields('id,name,category_id,thumbnail,warranty,cache_properties, price')->select(
			EAnd(ELike('category_path', EString('.laptop.')),EEqual('reference_id',EString(''))
				,ENE('price',EString(0)),ENE('min_price',EString(0)),ENE('market_price',EString(0)),ENE('status',EString(0)),ENE('quantity',EString(0)),ENE('thumbnail',EString(''))),
			array('order_by'=>'created_time desc', 'items_per_page'=>1)
			);
		}
		$items[] = $laptop_item;
		foreach($items as &$item)
		{
			$item['thumbnail'] = str_replace('210.245.80.62', '210.245.80.239', $item['thumbnail']);
			$item['cache_properties'].='<strong>Thời gian bảo hành</strong>:&nbsp;'.$item['warranty'].'&nbsp;tháng';

		}
		cache('estore_new_products', $items);
		return $items;
	}
	/**
     * Lấy danh sách sản phẩm
     *
     * @param int $store_id shop đang show
     * @return Array list sản phẩm
     */
	static function get_typical_products($store_id = '')
	{
		$file_name = 'data/'.portal()->id.'/product_categories.xml';
		if($data_categories = CTable('category')->select_all(EAnd(EEqual('feature', 1), ENE('parent_id', 0)), array('order_by' => 'id DESC', 'items_per_page'=>12))){
			foreach($data_categories as $k => $v){
				$v['idCate'] = $v['id'];
				$v['id'] = $v['char_seo'];
				$child_categories[$v['char_seo']] = $v;
			}
		}
		/*
		$child_categories = CTable('cats/cat/cats/cat/cats/cat[./is_homepage=1]')
			->change_store(new CDataXmlStore($file_name,'/root/'))->select_all(false, array('items_per_page'=>12));
		*/
		$categories = array();
		$count = 1;
		foreach ($child_categories as $key => $category)
		{
			if($count <= 9)
			{
				$products = CTable('product')->fields('id,name,thumbnail')->select_all(EAnd(EEqual('category_id', EString($category['id'])),ELIKE('types',EString('special')),EEqual('reference_id',EString('')), ENE('price',EString(0)),ENE('min_price',EString(0)),ENE('market_price',EString(0)),ENE('status',EString(0)),ENE('quantity',EString(0)),ENE('thumbnail',EString(''))),array('items_per_page'=>4, 'fields'=>'id, name, price,thumbnail','order_by'=>'sort_order desc'));
				if(!$products)
				{
					$products = CTable('product')->fields('id,name,thumbnail')->select_all(EAnd(EEqual('category_id', EString($category['id'])),EEqual('reference_id',EString('')), ENE('price',EString(0)),ENE('min_price',EString(0)),ENE('market_price',EString(0)),ENE('status',EString(0)),ENE('quantity',EString(0)),ENE('thumbnail',EString(''))),array('items_per_page'=>4, 'fields'=>'id, name, price,thumbnail','order_by'=>'sort_order desc'));
				}
				foreach($products as $id=>$product)
				{
					if(empty($category['thumbnail'])){
						$category['thumbnail'] = str_replace('210.245.80.62', '210.245.80.239', $product['thumbnail']);
					}
					$products[$id]['thumbnail'] = str_replace('210.245.80.62', '210.245.80.239', $product['thumbnail']);
				}
				if(count($products)>0){
					$categories[] = $category + array('products' => array_values($products));
					$count++;
				}
			}
		}
		cache('estore_typical_products', $categories);
		return $categories;
	}

	/**
	 * Get Estore property
	 *
	 * @param string $key
	 * @return mixed
	 */
	public function get($key) {
		return @$this->estore[$key];
	}
}

/**
 * Create new EStore
 *
 * @param unknown_type $options
 * @return CEstore
 */
function CEstore($options = array()){
	return CEstore::getInstance();
}
?>